package com.example.demo.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.config.DynamicDataSource;
import com.example.demo.dto.TaskDto;
import com.example.demo.entity.DataConnection;
import com.example.demo.entity.DatasourceConfig;
import com.example.demo.entity.DatasourceInfo;
import com.example.demo.mapper.TestMapper;
import com.example.demo.service.DataConnectionService;
import com.example.demo.service.DatasourceInfoService;
import com.example.demo.service.TestService;
import com.example.demo.utils.QuartzUtils;
import lombok.RequiredArgsConstructor;
import org.quartz.Scheduler;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author Administrator
 */
@Service
@RequiredArgsConstructor
public class TestServiceImpl extends ServiceImpl<TestMapper, DatasourceConfig> implements TestService {

    private final Scheduler scheduler;
    private final DynamicDataSource dynamicDataSource;
    private final DatasourceInfoService datasourceInfoService;
    private final DataConnectionService dataConnectionService;

    @Override
    public void addTask(TaskDto taskDto) {
        //创建任务
        QuartzUtils.createScheduleJob(scheduler,taskDto.getCron(),taskDto.getKey(),taskDto.getDesc());
    }

    @Override
    public List<DataConnection> select(String datasourceKey) {
        //切换到新数据源 datasourceKey为添加数据源是后的poolName
        DynamicDataSourceContextHolder.push(datasourceKey);
        return dataConnectionService.list();
    }

    @Override
    public void addDatasource() {
        //添加数据源，可以动态传入，这里方便查询数据库添加
        List<DatasourceInfo> datasourceInfos = datasourceInfoService.listByIds(ListUtil.toList(3, 4));
        datasourceInfos.forEach(d->{
            DataSourceProperty property = new DataSourceProperty();
            property.setUsername(d.getUsername());
            property.setPassword(d.getPassword());
            property.setUrl(d.getUrl());
            property.setDriverClassName(d.getDriver());
            property.setPoolName(d.getName());
            //添加新的数据源
            dynamicDataSource.setDataSources(property);
        });
    }
}
